<?php
class NoticesController extends AppController {

	public $name = 'Notices';
	
	public $helpers = array('Bayon', 'Bnotice');
	
	public $result = array( 'result' => '',
                            'message' => '',
                            'errors' => '',
                            'data' => ''
                            );
	
	public function beforeFilter(){
		parent::beforeFilter();
		$this->setLayout();
		$this->Auth->allow('*');
		
	}
	public function beforeRender() {
        
        $this->set( 'result', $this->result );   
    }
    public function admin_index(){
    	$this->paginate = array('limit' => 25, 'order' => 'Notice.id DESC');
    	
    	$this->Notice->recursive = 0;
		$this->set('notices', $this->paginate());
    }
	public function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid notice', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Notice->save($this->data)) {
				$this->Session->setFlash(__('The notices has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The notice could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Notice->read(null, $id);
		}
	}
/**
 * Section front page
 */	
    
	function index() {
		
	}
	
	public function remove(){

		if(!empty($this->data)){
			
			$this->Notice->id = $this->data['Remove']['notice_id'];
			$this->Notice->saveField('status', BAYON_NOTICE_STATUS_REMOVED);
			
			//remove all favor from this not
			$this->loadModel('Favor');
			$this->Favor->deleteAll(array('Favor.notice_id' => $this->data['Remove']['notice_id']), false);
			
			//update notice status on table UserStatus
			$this->noticeStatus('-');
			
			$this->result['result'] = 1;
			$this->result['message'] = __('Your notice was removed.', true);
			$this->result['data'] = $this->data['Remove']['notice_id']; 
		}
	}
	
	public function repeated(){
		
		if($this->RequestHandler->isAjax()){
			if(!empty($this->data)){
				$repeatedArray = explode('_', $this->data['Repeated']['user_notice']);
				$repeated['username'] = $repeatedArray[0];
				$repeated['notice_id'] =  $repeatedArray[1];
				
				$repeated_count = $this->Notice->find(
					'count',
					array(
						'conditions' =>array(
							'Notice.repeat_of' => $repeated['notice_id'],
							'Notice.user_id' => $this->Bayon->userId()
						)
						
					)
				);
				if($repeated_count > 0){
					$this->result['result'] = 0;
					$this->result['errors'] = "repeated";
					$this->result['message'] = __('This notice you have repeated', true);
				}else{
					$notice = $this->Notice->find(
						'first',
						array(
							'conditions' => array('Notice.id' => $repeated['notice_id']),
							'recursive' => -1
						)
					);
					
					//HTML render 
					$html_render = 'RP @<a href="'.$this->base.'/'.$repeated['username'].'">'.$repeated['username'].' </a>'.$notice['Notice']['render'];
					//initial for insert to notice table
					$this->data['Notice']['user_id'] = $this->Bayon->userId();
					$this->data['Notice']['message'] = $notice['Notice']['message'];
					$this->data['Notice']['created'] = date('Y-m-d h:i:s');
					$this->data['Notice']['render'] = $html_render;
					$this->data['Notice']['repeat_of'] = $repeated['notice_id'];
					$this->data['Notice']['source'] = BAYON_SOURCE_WEB;
					
					//open table to store
					$this->Notice->create();
				
					if ($this->Notice->save($this->data)) {
						
						$this->result['result'] = 1;
						$this->result['message'] = __('Your notice has been saved.', true);
						$this->result['data'] = $html_render;
						
						//update notice status on table UserStatus
						$this->noticeStatus('+');
					}else{
						$this->result['result'] = 0;
						$this->result['errors'] = "cannot save";
						$this->result['message'] = __('Your data cannot save. Please try again', true);
					}
				}
			}
		}else{
			$this->result['result'] = 0;
			$this->result['errors'] = "no_service";
			$this->result['message'] = __('Invalide Service', true);
		}
	}
/**
 * Reply Notice all submit by ajax
 * 
 */	
	public function reply(){
		
		if($this->RequestHandler->isAjax()){
			if(!empty($this->data)){
				
				$arrayReply = explode('_', $this->data['Reply']['user_notice']);
				$ar['username'] = '@'.$arrayReply[0];
				$ar['notice_id'] =  $arrayReply[1];
				
				$this->result['result'] = 1;
				$this->result['message'] = 'success';
				$this->result['data'] = $ar;
				
			}else{
				$this->result['result'] = 0;
				$this->result['message'] = __('Not engout data', true);
			}
		}else{
			$this->result['result'] = 0;
			$this->result['errors'] = "no_service";
			$this->result['message'] = __('Invalide Service', true);

		}
	}
/**
 * Update notice(status)
 * 
 */
	public function update() {
		if (!empty($this->data)) {
			if( $this->RequestHandler->requestedWith() == 'form' ){
				//HTML render 
				$html_render = $this->Bayon->bayonFilter( $this->data['Notice']['message'] );
				//initial for insert to notice table
				$this->data['Notice']['user_id'] = $this->Bayon->userId();
				$this->data['Notice']['created'] = date('Y-m-d h:i:s');
				$this->data['Notice']['render'] = $html_render;
				$this->data['Notice']['source'] = BAYON_SOURCE_WEB;
			}
			
			//open table to store
			$this->Notice->create();
			
			if ($this->Notice->save($this->data)) {
				
				$this->set('noticeId', $this->Notice->id);
				$this->set('render', $this->data['Notice']['render']);

                                // load Avatar model
                                $this->loadModel('Avatar');
                                $this->set('avatar', $this->Avatar->getAvatar($this->Bayon->userId(), AVATAR_WIDHT_48));
				
				//update notice status on table UserStatus
				$this->noticeStatus('+');
                                
				//success
				$this->result['result'] = 1;
				$this->result['message'] = __('The notice has been saved', true);
				//$this->result['data'] = '<a href="'.$this->base.'/'.$this->Bayon->username().'">'.$this->Bayon->username().' </a><p>'.$this->data['Notice']['render'].'</p>';
				
			} else {
				//fail
				$this->result['result'] = 0;
				$this->result['message'] = __('The notice could not be saved. Please, try again.', true);
				
			}
		}
	}
	
/**
 * Update notice status
 * 
 * @param unknown_type $id
 */	
	public function noticeStatus($oparator = '-'){

		//update status 
		$this->loadModel('UserStatus');
		if($oparator == '+'){
			//update following number
			$this->UserStatus->updateAll(
					array( 'UserStatus.value' => 'UserStatus.value + 1' ),
					array( 'UserStatus.user_id' => $this->Bayon->userId(), 'UserStatus.name_field' => STATUS_NOTICE )
			);
					
			//update user status session 
			$this->Session->write('User.Status.notice', $this->Session->read('User.Status.notice') + 1);
		}else{
			//update following number
			$this->UserStatus->updateAll(
					array( 'UserStatus.value' => 'UserStatus.value - 1' ),
					array( 'UserStatus.user_id' => $this->Bayon->userId(), 'UserStatus.name_field' => STATUS_NOTICE )
			);
					
			//update user status session 
			$this->Session->write('User.Status.notice', $this->Session->read('User.Status.notice') - 1);
		}
		
	}
	function view($id = null) {
		
		if (!$id) {
			$this->Session->setFlash(__('Invalid notice', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('notice', $this->Notice->read(null, $id));
	}
}
?>